﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using kmaraszkiewicz.Models;
using System.IO;

namespace kmaraszkiewicz.Controllers
{
    public class PhotoController : AdminController
    {
        private PortfolioEntities db = new PortfolioEntities();

        //
        // GET: /Photo/

        public PartialViewResult Index(int id)
        {
            ViewBag.ProjectId = id;
            return PartialView(db.Photos.Where(p => p.ProjectId == id).ToList());
        }

        //
        // GET: /Photo/Create

        public ViewResult Create(int id)
        {
            ViewBag.ProjectId = id;
            return View();
        }

        //
        // POST: /Photo/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                var projectId = Request.Form["ProjectId"];
                var photo = new Photo();
                var fileName = Path.GetFileName(file.FileName);
                photo.ExtensionType = Path.GetExtension(file.FileName);
                photo.Directory = Path.Combine("~/Content/Upload", fileName);
                photo.ProjectId = Convert.ToInt32(projectId);
                file.SaveAs(Path.Combine(Server.MapPath("~/Content/Upload"), fileName));
                db.Photos.Add(photo);
                db.SaveChanges();
                return RedirectToAction("Edit", "Project", new { id = photo.ProjectId });
            }

            return View();
        }

        //
        // GET: /Photo/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Photo photo = db.Photos.Find(id);
            if (photo == null)
            {
                return HttpNotFound();
            }
            return View(photo);
        }

        //
        // POST: /Photo/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Photo photo = db.Photos.Find(id);
            System.IO.File.Delete(Server.MapPath(photo.Directory));
            db.Photos.Remove(photo);
            db.SaveChanges();
            return RedirectToAction("Edit", "Project", new { id = photo.ProjectId });
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}